import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'login',
    component: ()=>import('@/views/login')
  },
  {
    path: '/home',
    meta:{
      auth:true,
    },
    name: 'home',
    component: ()=>import('@/views/home'),
    children:[
      {
        path:'/home',
        name: 'welcome',
        component: ()=>import('@/components/welcome')
      },
      {
        path:'/users',
        name: 'users',
        component: ()=>import('@/components/users')
      },
      {
        path:'/roles',
        name: 'roles',
        component: ()=>import('@/components/roles')
      },
      {
        path:'/rights',
        name: 'rights',
        component: ()=>import('@/components/rights')
      },
      {
        path:'/goods',
        name: 'goods',
        component: ()=>import('@/components/goods')
      },
      {
        path:'/goodsadd',
        name: 'goodsadd',
        component: ()=>import('@/components/goodsadd')
      },
      {
        path:'/params',
        name: 'params',
        component: ()=>import('@/components/params')
      },
      {
        path:'/categories',
        name: 'categories',
        component: ()=>import('@/components/categories')
      },
      {
        path:'/orders',
        name: 'orders',
        component: ()=>import('@/components/orders')
      },
      {
        path:'/reports',
        name: 'reports',
        component: ()=>import('@/components/reports')
      },
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 登录鉴权
router.beforeEach((to,form,next)=>{
  const flag = to.matched.some(item=>{
    return item.meta.auth
  })

  if(!flag){
    next()
  }else{
    const token = sessionStorage.getItem('token')
    if(!token){
      return next({
        path:'/'
      })
    }
    next()
  }
  next()
})


const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location){
  return originalPush.call(this,location).catch(err=>err)
}

export default router
